package com.limeng.datastruts.map;

import java.util.Map;

public class MyHashMap {

    public static void main(String[] args) {
        MyHashMap map = new MyHashMap();
        map.put("a1","aaaaaaaaa");
        map.put("w","w111111");
        map.put("www","w2222222222");
        System.out.println(map.get("w"));
        System.out.println(map.get("a1"));
        System.out.println(map.get("www"));
    }

    private static ListNode[] map;

    private static int size;

    private int capacity;

    public MyHashMap() {
        this.capacity = 16;
        map = new ListNode[capacity];
    }

    public void put(String key, Object value){
        if(size > capacity*0.75) {
            System.out.println("超过限制，需要扩容。。。");
            return;
        }
        int index = Math.abs(key.hashCode())%this.capacity;
        ListNode ln = map[index];
        if(ln==null){
            ListNode newLn = new ListNode(key,value);
            map[index] = newLn;
        }else{
            ln.addNode(key,value);
        }
        size++;
    }

    public Object get(String key){
        int index = Math.abs(key.hashCode())%this.capacity;
        ListNode ln = map[index];
        if(ln == null){
            return null;
        }
        return ln.getVal(key);
    }

    class ListNode{
        Node head;

        protected ListNode(String key,Object value) {
            this.head = new Node(key,value,null);
        }

        protected void addNode(String key,Object value){
            if(head==null) return;
            Node node = new Node(key,value,null);
            Node tmp = head;
            while (true){
                if (tmp.key.equals(key)){
                    tmp.value = value;
                }
                if (tmp.next==null){
                    break;
                }
                tmp = tmp.next;
            }
            tmp.next = node;
        }

        protected Object getVal(String key){
            if(head==null) return null;
            if (head.next==null){
                return head.value;
            }
            else {
                Node tmp = head;
                while (tmp!=null){
                    if(tmp.key.equals(key)){
                        return tmp.value;
                    }
                    tmp = tmp.next;
                }
                return null;
            }
        }
    }

    class Node{
        private String key;
        private Object value;
        private Node next;

        protected Node(String key, Object value, Node next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }
}
